package com.ling.util;

import com.ling.bean.Blog;
import com.ling.bean.Question;
import com.ling.dto.RecommendationDto;
import com.ling.service.BlogService;
import com.ling.service.QuestionService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class ElasticSearchUtil {
    @Autowired
    private BlogService blogService;
    @Autowired
    private QuestionService questionService;

    private RestTemplate restTemplate = new RestTemplate();

    @Test
    public void testInsertBlog() {
        //获取所有博客，循环插入elasticsearch数据库中
        List<Blog> latestBlogs = blogService.getLatestBlogs();
        RecommendationDto recommendationDto ;
        for (Blog blog : latestBlogs) {
            String url = "http://localhost:9200/blog/blog/" + blog.getId();
            System.out.println("正在存放博客"+blog.getId());
            recommendationDto = new RecommendationDto();
            recommendationDto.setId(blog.getId());
            recommendationDto.setContent(blog.getBlogcontent().replaceAll("<[.[^<]]*>", ""));
            recommendationDto.setTitle(blog.getBlogtitle());
            recommendationDto.setType(1);
            restTemplate.put(url,recommendationDto);
        }
    }

    @Test
    public void testInsertQuestion() {
        List<Question> allQuestions = questionService.getAllQuestions();
        RecommendationDto recommendationDto ;
        for (Question question : allQuestions) {
            String url = "http://localhost:9200/question/question/" + question.getId();
            System.out.println("正在存放问题"+question.getId());
            recommendationDto = new RecommendationDto();
            recommendationDto.setId(question.getId());
            recommendationDto.setType(0);
            recommendationDto.setTitle(question.getQuestiontitle());
            recommendationDto.setContent(question.getQuestioncontent().replaceAll("<[.[^<]]*>", ""));
            restTemplate.put(url,recommendationDto);
        }
    }
}
